package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.exceptions.LyException;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Autowired
    private BrandService brandService;

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        //健壮性判断
        page = Math.max(1, page);
        rows = Math.max(5, rows);
        //搜索是否有关键字
        boolean isNotBlank = StringUtils.isNoneBlank(key);
        //select * from tb_brand b
        Page<Brand> result = query().
                //where b.`name` like "%x%"or b.letter="x"
                        like(isNotBlank, "name", key)
                .or()
                .like(isNotBlank, "letter", key)
                //limit 0,5
                .page(new Page<>(page, rows));
        //解析
        long total = result.getTotal();
        long totalPages = result.getPages();
        List<Brand> list = result.getRecords();
        //封装并返回
        return new PageDTO<>(total, totalPages, BrandDTO.convertEntityList(list));
    }

    @Override
    public List<BrandDTO> queryBrandByCategoryId(Long categoryId) {
        List<Brand> list = getBaseMapper().queryBrandByCategoryId(categoryId);
        return BrandDTO.convertEntityList(list);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        //把dto变成怕po
        Brand brand = brandDTO.toEntity(Brand.class);
        boolean success = save(brand);
        if (!success) {
            throw new LyException(500, "新增品牌失败!");
        }
        //回显id
        Long brandId = brand.getId();
        //中间表新增
        //获取与品牌有关的所有分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        //把分类id与品牌id组合，封装为categoryBrand
        List<CategoryBrand> categoryBrands = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }
        //批量新增
        categoryBrandService.saveBatch(categoryBrands);
    }

    /**
     * 更新品牌
     *
     * @param brandDTO
     */
    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //把dto变成怕po
        Brand brand = brandDTO.toEntity(Brand.class);
        // 更新品牌
        boolean success = updateById(brand);
        if (!success) {
            throw new LyException(500, "更新品牌失败！");
        }

        Long brandId = brandDTO.getId();
        // 根据品牌id删除中间表数据
        success = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!success) {
            throw new LyException(500, "更新品牌失败，删除中间表数据出错");
        }
        // 重新插入中间表数据
        List<Long> categoryIds = brandDTO.getCategoryIds();
        List<CategoryBrand> categoryBrands = categoryIds.stream()
                .map(id -> CategoryBrand.of(id, brandId)).collect(Collectors.toList());
//        List<CategoryBrand>categoryBrands = new ArrayList<>(categoryIds.size());
//        for (Long categoryId : categoryIds) {
//            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
//            categoryBrands.add(categoryBrand);
//        }
        // 批量写入中间表数据
        categoryBrandService.saveBatch(categoryBrands);
    }

    /**
     * 根据ID删除品牌
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteBrandById(Long id) {
        brandService.removeById(id);
        categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
    }

}
